package com.example.qcrmdemo.Controller;

import com.example.qcrmdemo.entity.Role;
import com.example.qcrmdemo.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class RoleController {
    private static final Logger logger= LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private RoleService roleService;

    @GetMapping("/XiTongGuanLi/role_list")
        public ModelAndView RoleView(
            @RequestParam(name="pageNum",required = true,defaultValue = "1")int pageNum,
            @RequestParam(name="pageSize",required = true,defaultValue = "5")int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ){
        ModelAndView mav=new ModelAndView("XiTongGuanLi/role_list");
        PageInfo<Role> page=roleService.findByKeyword(pageNum,pageSize,keyword);

        mav.addObject("page",page);
        return mav;
        }
     @GetMapping("/XiTongGuanLi/role_add")
    public ModelAndView RoleAddView(){
        ModelAndView mav=new ModelAndView("XiTongGuanLi/role_add");
        return mav;
     }

    @PostMapping("/XiTongGuanLi/role_add")
    //@Validated注解所标注的参数，表明该参数中的属性值必须按照属性上定义柜子进行验证
    //验证结果会以BindingResult实例的形式传入该方法中
    public ModelAndView roleAdd(@Validated Role role, BindingResult bindingResult){

        //redirect表示重定向响应
        //给游览器仅发送一个请求地址，没有任何视图内容和数据
        //游览器会使用收到的地址，重新发送一个Get请求，由于是请求，因此没有缓存上一次请求的数据，从而防止重复提交表单的目的
        ModelAndView mav=new ModelAndView("redirect:/XiTongGuanLi/role_add");

        Map<String,String > errorMessages=new HashMap<>();
        if(bindingResult.hasErrors()){
            //如果验证有错误信息，那么要进行处理
            //获得出现的错误,以及响应的错误消息文本
            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //将错误信息放入到映射中
            for(FieldError error:fieldErrors){
                //从每一个域错误对象中取出域名称，错误消息，加入映射集合中
                errorMessages.put(error.getField(),error.getDefaultMessage());
            }
            //将错误信息发送给视图
            mav.addObject("errorMessages",errorMessages);
            //将客户填写的信息重新显示在表单
            mav.addObject("role",role);
            //由于没有保存数据，因此不必信息重定向。
            mav.setViewName("XiTongGuanLi/role_add");
        }else {
            //调用服务方法保存客户数据
            boolean result= roleService.append(role);
            if(result){
                logger.info("新增用户信息成功"+role);
            }else {
                logger.info("新增用户信息失败"+role);
            }
        }
        //调用服务方法保存客户数据

        return mav;

    }

    /**
     * 修改用户信息
     * @param id
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @GetMapping("/XiTongGuanLi/role_modify")
    public ModelAndView roleModifyView(
            @RequestParam(name = "id",required = true) int id,
            @RequestParam(name="pageNum",required = true,defaultValue = "1")int pageNum,
            @RequestParam(name="pageSize",required = true,defaultValue = "5")int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ){
        ModelAndView mav=new ModelAndView("XiTongGuanLi/role_modify");
        Role role=roleService.findById(id);

        mav.addObject("role",role);
        return mav;
    }

    @PostMapping("/XiTongGuanLi/role_modify")
    public ModelAndView roleModify(
            Role role,
            @RequestParam(name="pageNum",required = true,defaultValue = "1")int pageNum,
            @RequestParam(name="pageSize",required = true,defaultValue = "5")int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ) throws UnsupportedEncodingException {
        String urlredirect="redirect:/XiTongGuanLi/role_list?pageNum="+pageNum+"&pageSize="+pageSize+"&keyword="+ URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav=new ModelAndView(urlredirect);
        boolean result=roleService.modify(role);
        return mav;
    }

    /**
     * 删除用户
     * @param id
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/XiTongGuanLi/role_remove")
    public ModelAndView roleRemove(
            @RequestParam(name = "id",required = true) int id,
            @RequestParam(name="pageNum",required = true,defaultValue = "1")int pageNum,
            @RequestParam(name="pageSize",required = true,defaultValue = "5")int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ) throws UnsupportedEncodingException {
        String urlredirect="redirect:/XiTongGuanLi/role_list?pageNum="+pageNum+"&pageSize="+pageSize+"&keyword="+ URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav=new ModelAndView(urlredirect);
        boolean result=roleService.remove(id);
        return mav;
    }
}
